package com.team.recruitment_management_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.team.recruitment_management_system.mapper.FileMapper;
import com.team.recruitment_management_system.pojo.entity.File;
import com.team.recruitment_management_system.service.FileService;
import com.team.recruitment_management_system.util.FileUploadUtils;
import com.team.recruitment_management_system.util.FileUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;

@Service
public class UploadFileServiceImpl implements FileService {
    @Autowired
    FileMapper fileMapper;

    public String replaceFilename(String name){
        String baseName;
        int dotIndex = name.lastIndexOf('.'); // 找到最后一个点的位置
        if (dotIndex != -1) {
            // 如果找到了点，则截取文件名（不包括点及其后面的字符）
            baseName = name.substring(0, dotIndex);
        } else {
            // 如果没有找到点，说明文件名没有后缀，直接使用原始文件名
            baseName = name;
        }
        return baseName;
    }
    @Override
    public void upload(MultipartFile file, String baseDir) throws Exception {
        //就算什么也不传，controller层的file也不为空，但是originalFilename会为空（亲测）
        String originalFilename = file.getOriginalFilename();

        if(originalFilename == null || "".equals(originalFilename)) {
            throw new Exception( "上传文件不能为空");
        }
        //检测是否上传过同样的文件，如果有的话就删除。（这边可根据个人的情况修改逻辑）
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("old_name", originalFilename);
        File oldEntity = fileMapper.selectOne(queryWrapper);

        //新的文件
        File uploadEntity = new File();
        uploadEntity.setCreateTime(new Date());
        uploadEntity.setUpdateTime(new Date());
        uploadEntity.setOldName(file.getOriginalFilename());        //这边可以根据业务修改，项目中不要写死
        //设置存储的文件名为去掉后缀的形式
        uploadEntity.setName(replaceFilename(originalFilename));
        String fileLocation = null ;
        if(baseDir != null) {
            fileLocation = FileUploadUtils.upload(baseDir, file);
        }else {
            fileLocation = FileUploadUtils.upload(file);
        }

        uploadEntity.setLocation(fileLocation);
        fileMapper.insert(uploadEntity);

        if(oldEntity != null) {
            //确保新的文件保存成功后，删除原有的同名文件(实体文件 and 数据库文件)
            FileUtils.deleteFile(oldEntity.getLocation());
            fileMapper.deleteById(oldEntity.getId());
        }
    }



    @Override
    public boolean download(HttpServletResponse response, String newName) throws IOException {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        //自定义存储在数据库中的名字
        queryWrapper.eq("name", newName);
        File uploadEntity = fileMapper.selectOne(queryWrapper);
        if (uploadEntity == null){
            return false;
        }
        String encodedFileName = URLEncoder.encode(uploadEntity.getOldName(), "UTF-8");
        response.setContentType("application/octet-stream");        //这边可以设置文件下载时的名字，我这边用的是文件原本的名字，可以根据实际场景设置
        response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
        try {

            FileUtils.writeBytes(uploadEntity.getLocation(), response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    }


}
